package com.example.feigntest.customconfig.encoder;

import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;

import com.example.feigntest.customconfig.requestinterceptor.CustomFeignRequestInterceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;

import java.lang.reflect.Type;

/**
 * 描述：Feign 编码器,负责将对象编码到请求体中
 *
 * @author YangQun by 2020/10/17
 */
public class CustomFeignEncoder implements Encoder {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    /**
     * @param object   以 com.example.feigntest.feignclient.EncoderTestClient 为例,
     *                 这个 object 就是参数中的 order 对象
     * @param bodyType bodyType 就是 object 的类型
     * @param template 用法和 {@link CustomFeignRequestInterceptor#apply} 中template一样
     * @throws EncodeException when encoding failed due to a checked exception.
     */
    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        log.info("CustomFeignEncoder object class = {}", object.getClass().getName());

        log.info("CustomFeignEncoder bodyType = {}", bodyType);

        // SpringEncoder 会根据 HttpMessageConverter 转换对象, 这里会把对象转成 json
        new SpringEncoder(messageConverters).encode(object, bodyType, template);
    }
}
